<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24/024
 * Time: 22:38
 */
namespace app\api\model;
use think\Model;
use think\facade\Url;
use think\Loader;
use think\Db;
use app\common\model\Currency;
use phpqrcode\QRcode;

class Member extends Base
{
    
    /**
    * 绑定师徒关系
    * @param mid int 会员id
    * @param param array 参数数组
    * @param config array 系统参数
    * @return bool
    */
    public function _bindRelation($mid, $param , $config){
        //var_dump($param);die;
        if(!isset($param['incode'])){
            $this->error = '参数错误';
            return false;
        }
        
        $incode = unserialize(base64_decode($param['incode']));
        
        if(empty($incode['unique']) || empty($incode['code'])){
            $this->error = '参数错误';
            return false;
        }
        $unique = base64_decode($incode['unique']);
        $code = base64_decode($incode['code']);
        //var_dump($unique);
        //var_dump($code);
        $invitation_code = $code;
        
        //测试未加密
        //$unique = base64_decode($unique);
        //$invitation_code = base64_decode($invitation_code);

        //业务逻辑，
        /* 
        *  1.子账号是否有师傅，子账号若有徒弟则无法拜师
        *  2.子账号是否是新会员，
        *  3.是否为同一账号，
        *  4.判断师傅账号是否可用，
        *  5.是否是否达到收徒上限
        *  6.新用户才能拜师
        *  7.绑定关系不能闭环
        */
        $child_data = $this->field('pid, is_new')->where([['id', '=', $mid]])->find();
        if(!empty($child_data['pid'])){
            $this->error = "已经有师傅";
            return false;
        }
        
        $my_child = $this->field('id')->where([['pid', '=', $mid]])->find();
        if(!empty($my_child)){
            $this->error = "已经有徒弟，不能拜师";
            return false;
        }
        
        
        if($child_data['is_new'] != 1){
            $this->error = "只有新用户才能拜师";
            return false;
        }
        
        $pdata = $this->where([['unique', '=', $unique], ['invitation_code', '=', $invitation_code], ['status', '=', 1]])->find();
        //var_dump($this->getLastSql());die;
        if($pdata['id'] == $mid){
            $this->error = "同一账号不能绑定";
            return false;
        }
        
        if(empty($pdata)){
            $this->error = "该师傅账号不存在或冻结";
            return false;
        }
        
        $pid = $pdata['id'];
        
        $model_info = New MemberInfo;
        $pinfo = $model_info->_getInfoByMid($pid);
        
        $child_num = isset($pinfo['apprentice_num']) ? $pinfo['apprentice_num'] : 0;
        $max_num = $config['APPRENTICE_MAX'];
        if($child_num >= $max_num){
            $this->error = "师傅收徒数量已上限";
            return false;
        }
        
        //达到要求则绑定试图关系
        /*
        * 1.绑定师徒关系
        * 2.校验是否是第一个徒弟，若是第一次收徒，则师傅直接得相应的余额奖励
        * 3.更新师傅平台信息数据
        * 4.更新师傅余额
        */
        $this->startTrans();
        
        $sql = "update sy_member as m set m.pid=$pid where m.id = $mid and m.pid = 0 and m.is_new = 1 and m.status = 1 and m.is_top = -1 and (select apprentice_num from sy_member_info mi where mi.mid = $pid) < $max_num and (select * from(select p.status as pstatus from sy_member p where p.id = $pid) as TEMP)  = 1";
        //echo $sql;die;
        $ret = Db::execute($sql); //绑定师徒关系
        if(!$ret){
            $this->error = '关系绑定失败';
            return false;
        }

        $money = 0;
        $ip = ip2long(get_ip());
        $serial_number = date("YmdHis").uniqid();
        $remark = "首次收徒获得奖励";
        $image = $config['DEFAULT_TASK_IMG'];
        $time = time();
        
        if($child_num == 0){
            $money = $config['FIRST_APPRENTICE_REWARD'];
            $sql = "insert sy_balance_record(mid, type_id, child_id, serial_number, money, image, remark,ip, created) select $pid, 2, $mid, '$serial_number', '$money', '$image', '$remark', $ip, $time from sy_member_info mi where mi.apprentice_num = 0 and mi.mid = $pid limit 1";
            
            $ret = Db::execute($sql);
            if(!$ret){
                $this->error = '师傅余额记录写入失败';
                return false;
            }

            $sql1 = "update sy_member set balance = balance + $money where id = $pid and (select mi.apprentice_num from sy_member_info mi where mi.mid = $pid) = 0";
            
            $ret = Db::execute($sql1);
            if(!$ret){
                $this->error = '师傅金额更新失败';
                return false;
            }
            
            $sql1 = "update sy_member_info set apprentice_return_commission_balance_today = apprentice_return_commission_balance_today + $money, apprentice_return_commission_balance = apprentice_return_commission_balance + $money where mid = $pid and apprentice_num = 0";
            
            $ret = Db::execute($sql1);
            if(!$ret){
                $this->error = '师傅金额更新失败';
                return false;
            }
            

            
        }
        
        $sql = "update sy_member_info set apprentice_num = apprentice_num + 1, total_balance = total_balance + $money where mid = $pid";
        
        $ret = Db::execute($sql);
        if(!$ret){
            $this->error = '师傅徒弟数量更新失败';
            return false;
        }
        
        $model = new Currency;
        $ret = $model->_memberUpgrade($pid);
        if(!$ret){
            $this->error = '师傅等级更新失败';
            return false;
        }
        
        $time = time();
        $sql = "insert sy_mentor(pid, cid, profit, created) select $pid, $mid, $money, $time from DUAL where  NOT EXISTS (select pid, cid, created from sy_mentor  where pid = $pid and cid = $mid)";
        $ret = Db::execute($sql);
        if(!$ret){
            $this->error = '收徒失败';
            return false;
        }

        $this->commit();
        $member = $this->_getInfoById($mid);
        return $member;
    }
    
    /**
    * 注册
    * @param tel string 手机号
    * @param code string 验证码
    * @param pwd string 密码
    * @param pwd1 string 确认密码
    * @param 
    */
    public function _reg($tel, $code, $pwd, $pwd1 ){
        if(!preg_match("/^(13|14|15|16|17|18|19)[0-9]{9}$/", $tel)){
            $this->error = "请输入合法的手机号";
            return false;
        }
        if(!preg_match("/^[0-9a-zA-Z]{6,16}$/", $pwd)){
            $this->error = "请输入6至16位的密码";
            return false;
        }
        if(empty($code)){
            $this->error = "请输入验证码";
            return false;
        }
        
        if(strcmp($pwd, $pwd1)){
            $this->error = "两次密码不一致";
            return false;
        }
        
        $baseModel = new Base;
        $config = $baseModel->getConfig();
        
        $codeModel = new TelCode();
        $ret = $codeModel->_checkCode($tel, $code, 1);
        if(!$ret){
            $this->error = $codeModel->getError();
            return false;
        }
        
        $data = $this->_getByTel($tel);
        if(!empty($data)){
            $this->error = '手机号已存在';
            return false;
        }
        //手机号不存在则注册用户
        
        //直接注册步骤：1.写入会员，2创建token，3创建会员资料，4创建会员平台统计信息，
        $unique = strtoupper(nocstr(10));
        $this->unique($unique);
        $invitation_code = strtoupper(nocstr(10));
        $this->invitation_code($invitation_code);
        
        $currencyModel = new Currency;
        $qrcode = $currencyModel->_qrcode($unique,$invitation_code);
        $data = [
            'pwd'    => createPassword($pwd),
            'unique' => $unique,
            'user_name' => $tel,
            'invitation_code' => $invitation_code,
            'qrcode' => $qrcode,
            'updated' => time(),
            'created' => time(),
        ];
        $this->startTrans();
        $ret = $this->save($data);
        if(!$ret){
            $this->error = '登录失败';
            $this->rollback();
            return false;
        }
        
        $mid = $this->getLastInsID();
        //var_dump($mid);
        $token_ob = new Token;
        $ret1 = $token_ob->_createToken($mid);
        //var_dump($ret1);die;
        if(!$ret1){
            $this->error = $token_ob->getError();
            $this->rollback();
            return false;
        }
        $profile_model = new MemberProfile;
        $ret2 = $profile_model->_addProfile($mid, $config['DEFAULT_HEAD']);
        if(!$ret2){
            $this->error = $profile_model->getError();
            $this->rollback();
            return false;
        }
        
        //4.创建会员平台统计信息
        $info_model = new MemberInfo;
        $ret3 = $info_model->_addInfo($mid);
        if(!$ret3){
            $this->error = $info_model->getError();
            $this->rollback();
            return false;
        }
        
        $this->commit();
        
        $member = $this->_getInfoById($mid);

        return $member;
    }
    

    /**
    * 忘记密码
    */
    public function _forget($tel, $code, $pwd){
        if(!preg_match("/^(13|14|15|16|17|18|19)[0-9]{9}$/", $tel)){
            $this->error = "请输入合法的手机号";
            return false;
        }
        if(!preg_match("/^[0-9a-zA-Z]{6,16}$/", $pwd)){
            $this->error = "请输入6至16位的密码";
            return false;
        }
        if(empty($code)){
            $this->error = "请输入验证码";
            return false;
        }
        
        $data = $this->_getByTel($tel);
        if(empty($data)){
            $this->error = '手机号不存在';
            return false;
        }
        
        if($data['status'] != 1){
            $this->error = '该账号被冻结';
            return false;
        }
        
        $codeModel = new TelCode();
        $ret = $codeModel->_checkCode($tel, $code, 3);
        if(!$ret){
            $this->error = $codeModel->getError();
            return false;
        }
        
        $pwd = createPassword($pwd);
        $ret = $this->where(['user_name'=>$tel])->update(['pwd'=>$pwd, 'updated'=>time()]);
        if(!$ret){
            $this->error = '更新密码失败';
            return false;
        }
        
        return true;
        
    }
    
    /**
    * 修改密码
    * @param mid int 会员id
    * @param tel string 手机号
    * @param code string 验证码
    * @param pwd string 密码
    * @param pwd1 string 确认密码
    * @param 
    */
    public function _editPwd($mid, $tel, $code, $pwd, $pwd1 ){
        if(!preg_match("/^(13|14|15|16|17|18|19)[0-9]{9}$/", $tel)){
            $this->error = "请输入合法的手机号";
            return false;
        }
        if(!preg_match("/^[0-9a-zA-Z]{6,16}$/", $pwd)){
            $this->error = "请输入6至16位的密码";
            return false;
        }
        if(empty($code)){
            $this->error = "请输入验证码";
            return false;
        }
        
        if(strcmp($pwd, $pwd1)){
            $this->error = "两次密码不一致";
            return false;
        }
        
        $baseModel = new Base;
        $config = $baseModel->getConfig();
        
        $codeModel = new TelCode();
        
        $this->startTrans();
        $ret = $codeModel->_checkCode($tel, $code, 4);
        if(!$ret){
            $this->error = $codeModel->getError();
            return false;
        }
        
        $data = $this->_getByTel($tel);
        if(empty($data)){
            $this->error = '手机号不存在';
            return false;
        }
        
        if($data['id'] != $mid){
            $this->error = '请输入您绑定的手机号';
            return false;
        }
        
        $pwd = createPassword($pwd);
        $ret = $this->where(['id'=>$mid,'user_name'=>$tel, 'status'=>1])->update(['pwd'=>$pwd, 'updated'=>time()]);
        if(!$ret){
            $this->error = '密码修改失败';
            return false;
        }
        $this->commit();
        return true;
    }

    /**
    * 更新设备ID
    * @param mid int 会员id
    * @param device_id string 设备ID
    */
    public function _updateDeviceID($mid, $device_id){
        $data = $this->where([['id', '=', $mid]])->find();
        $data->device_id = $device_id;
        $ret = $data->save();
        if(!$ret){
            $this->error = "设备号更新失败";
            return false;
        }
        
        return true;
    }
    
    
    /**
    * 会员登录
    * @param tel string 手机号
    * @param pwd string 密码
    */
    public function _login($tel, $pwd){
        if(empty($pwd)){
            $this->error = '缺少验证码';
            return false;
        }
        if(!preg_match("/^(13|14|15|16|17|18|19)[0-9]{9}$/", $tel)){
            $this->error = '请填写合法的手机号';
            return false;
        }
        
        //校验验证码
        $code_model = New TelCode();
        /*$ret = $code_model->_checkCode($tel, $code, 2);
        if(!$ret){
            $this->error =  $code_model->getError();
            return false;
        }*/
        
        $member = $this->_getByTel($tel);
        if(empty($member)){
            $this->error = "手机号不存在";
            return false;
        }else{
            //存在则刷新token，更新会员udid记录，登录设备udid
            $mid = $member->id;

            $ge_password = createPassword($pwd);
            $data_password = $member->pwd;
            if($data_password!=$ge_password){
                $this->error = "密码错误";
                return false;
            }
            $this->startTrans();
            $token_ob = new Token;
            $ret1 = $token_ob->_createToken($mid);
            if(!$ret1){
                $this->error = $token_ob->getError();
                $this->rollback();
                return false;
            }
            
            $model = new Sign();
            $ret4 = $model->_setSignContinueNum($mid);
            if(!$ret4){
                $this->error = $model->getError();
                return false;
            }
            
            $model = new MemberInfo();
            $ret = $model->_setLoginContinueNum($mid);
            if(!$ret){
                $this->error = $model->getError();
                return false;
            }
            
            $this->where(['id'=>$mid])->update(['last_login_time'=>time()]);
            $this->commit();
        
            $member = $this->_getInfoById($mid);

            return $member;

        }
        //校验验证码
        
    }
    
    /**
    * 更新会员udid
    * @param id int 会员id
    * @param udid string 会员udid
    */
    public function _updateUdid($id, $udid){
        $data =  $this->where([['id', '=', $id]])->find();
        $data->udid = $udid;
        $data->last_login_time = time();
        $ret = $data->save();
        if(!$ret){
            $this->error = 'udid更新失败';
            return false;
        }
        
        return true;
    }
    
    /**
    * 通过手机号查找用户
    * @param tel string 手机号
    * @return array
    */
    public function _getByTel($tel){
        return $this->where([['user_name', '=', $tel]])->find();
    }
    
    /**
    * 通过udid查找用户
    * @param udid string 用户udid
    * @return array
    */
    public function _getByUdid($udid){
        return $this->where([['udid', '=', $udid]])->find();
    }
    
    
    

    
    /**
    *   生成唯一平台标识
    *   @param unique string 平台唯一ID
    *   @return string
    */
    public function unique($unique){
        $user = $this->where(array('unique'=>$unique))->find();
        if(!empty($user)){
            $unique = strtoupper(nocstr(10));
            $this->unique($unique);
        }else{
            return $unique;
        }
    }
    
    /**
    *   生成邀请码
    *   @param unique string 平台唯一ID
    *   @return string
    */
    public function invitation_code($invitation_code){
        $user = $this->where(array('invitation_code'=>$invitation_code))->find();
        if(!empty($user)){
            $invitation_code = strtoupper(nocstr(10));
            $this->invitation_code($invitation_code);
        }else{
            return $invitation_code;
        }
    }
    
    
    /**
    * 用户ID获取用户信息
    * @param mid int 用户ID
    * @return array 用户信息
    */
    public function _getInfoById($mid){
        
        $arr = [
            'mi.apprentice_num',
            'mi.apprentice_return_commission_balance_today',
            'mi.apprentice_return_commission_balance',
            'mi.login_num',
            'mi.login_num_today',
            'mi.login_continuity_num',
            'mi.sign_num',
            'mi.sign_continuity_num',
            'mi.sign_continuity_seven_num',
            'mi.finish_task_num',
            'mi.finish_task_balance',
            'mi.withdraw_balance',
            'mi.exchange_balance',
            'mi.onday_turntable_num',
            'mi.total_balance',
            'mi.total_gold',
        ];
        $str = implode(',',$arr);
        $data = $this->alias('m')
            ->field('m.*, ml.title as level_name, t.token, mp.image, mp.nick_name, mp.email, mp.sex, mp.pid as pdd, mp.cid, mp.address,mp.birthday, mp.birthdayint,'.$str)
            ->join('token t', 'm.id=t.mid', 'LEFT')
            ->join('member_level ml', 'm.level_id=ml.id', 'LEFT')
            ->join('member_profile mp', 'm.id=mp.mid', 'LEFT')
            ->join('member_info mi', 'm.id=mi.mid', 'LEFT')
            ->where([['m.id', '=', $mid]])
            ->find();
            //var_dump($data['qrcode']);die;
        $data['qrcode'] = getImage($data['qrcode']);
        
        /*$model = new Currency;
        $unique = $data['unique'];
        $invitation_code = $data['invitation_code'];
        $qrcode = $model->_qrcode($unique,$invitation_code);*/

        $data['share_url'] = url('api/login/ureg',"",'',true)."?unique=".base64_encode($data['unique'])."&code=".base64_encode($data['invitation_code']);
        return $data;
    }
    
    /**
    * 校验用户是否冻结
    * @param id 用户id
    * @return bool
    */
    public function _check($id){
        $data = $this->where([['id', '=', $id]])->find();
        if($data['status'] == -1){
            $this->error = '用户被冻结';
            return false;
        }
        if($data['is_del'] == 1){
            $this->error = '账号不存在';
            return false;
        }
        
        return true;
    }

    /*
    * 通过用id查找udid
    */
    public function _getUdidByID($mid){
        $data =  $this->field('udid')->where([['id', '=', $mid]])->find();
        return $data['udid'];
    }
    
    /*
    * 通过用id查找简洁信息
    */
    public function _getBreifByID($mid){
        $data =  $this->where([['id', '=', $mid]])->find();
        return $data;
    }
    
    /**
    * 更新用户真实信息
    * @param mid 用户id
    * @param real_name 真实姓名
    * @return bool
    */
    public function _updateRealName($mid, $real_name){
        $this->startTrans();
        $member = $this->_getBreifByID($mid);
        $member->is_real_name = 1;
        $ret = $member->save();
        if($ret === false){
            $this->error = '真实姓名更新失败';
            return false;
        }
        
        $model = new MemberProfile;
        $model->_updateRealName($mid, $real_name);
        if(!$ret){
            $this->error = $model->getError();
            return false;
        }
        
        $this->commit();
        return true;
    }
    
    

    
    /**
    * 申请提现
    * @param int mid 会员id
    * @param string udid IOS UDID
    * @param int money 提现金额
    * @param int type 提现类型 1支付宝，2微信
    * @return bool
    */
    public function _applyWithdraw($mid, $udid, $money, $type){
        if(!in_array($type, [1,2])){
            $this->error = '参数错误';
            return false;
        }

        $remark = "";
        if($type == 1){
            $remark = "提现到支付宝";
        }elseif($type == 2){
            $remark = "提现到微信";
        }
        $type_id = 4;
        $serial_number = serialNumber();
        $ip = get_ip();
        $ip = ip2long($ip);
        $time = time();
        
        $this->startTrans();
        $m = -$money;
        $sql = "insert sy_balance_record(mid, udid, type_id, serial_number, money, remark, ip, created) select $mid, '$udid', $type_id, '$serial_number', $m, '$remark', $ip, $time from sy_member where id = $mid and balance >= $money";
        $ret = Db::execute($sql);
        if(!$ret){
            $this->error = '余额不足';
            return false;
        }
        
        $bid = Db::name('balance_record')->getLastInsID();
        $sql = "insert sy_apply_with(mid, bid, type_id, money, ip, created) select $mid, $bid, $type, $money, $ip, $time from sy_member where id = $mid and balance >= $money";
        
        $ret = Db::execute($sql);
        if(!$ret){
            $this->error = '余额不足';
            return false;
        }
        
        $sql= "update sy_member set balance = balance - $money where id = $mid and balance >= $money";
        
        $ret = Db::execute($sql);
        if(!$ret){
            $this->error = '余额不足';
            return false;
        }
        $sql= "update sy_member_info set withdraw_balance = withdraw_balance + $money where mid = $mid";
        
        $ret = Db::execute($sql);
        if(!$ret){
            $this->error = '余额不足';
            return false;
        }
        
        $this->commit();
        return true;
    }
    
 
    
    /**
    * 绑定支付宝账号
    * @param int mid 会员id
    * @param account string 支付宝账号
    * @param realName string 支付宝认证姓名
    */
    public function _bindAli($mid, $account, $realName){
        $data = $this->field('id')->where([['ali_account', '=', $account]])->find();
        if(!empty($data)){
            $this->error = '该支付宝账号已存在';
            return false;
        }
        
        $member = $this->where([['id', '=', $mid]])->find();
        if(empty($member)){
            $this->error = '该账号不存在';
            return false;
        }
        if($member['status'] != 1){
            $this->error = '该账号被冻结';
            return false;
        }
        if($member['is_ali'] == 1){
            $this->error = '该已绑定支付宝';
            return false;
        }
        $update = [
            'ali_account' => $account,
            'ali_name' => $realName,
            'is_ali' => 1,
        ];
        
        $where = [
            'is_ali' => -1,
            'id' => $mid,
        ];
        $ret = $this->save($update, $where);
        
        if(!$ret){
            $this->error = '账号绑定失败';
        }
        return true;
    }
    
    /**
    * 会员注销
    * @param mid int 会员id
    * @return bool
    */
    public function _cancellation($mid){
        $ret = $this->where(['id'=>$mid])->update(['is_del'=>1]);
        if(!$ret){
            $this->error = '注销失败';
            return false;
        }
        
        return true;
    } 
    
    /**
    *
    */
    


}